#include "cbrowserapp.h"
#include "cbrowserwindow.h"

#include <buola/dbus/cproxy.h>
#include <buola/io/curi.h>
#include <buola/algorithm/container.h>

namespace buola { namespace browser {

CCmdLineFlag CBrowserApp::mOptionService("service",L"launches as service, which doesn't open any window");

CBrowserApp::CBrowserApp()
    :   dbus::CObject<CBrowserApp>("/org/buola/Browser")
{
}

CBrowserApp::~CBrowserApp()
{
}

bool CBrowserApp::Activate()
{
    if(dbus::get_session_bus()->RegisterService("org.buola.Browser")) return true;

    //if we can't register... recycle existing browser
    dbus::CProxy lProxy(dbus::get_session_bus(),"org.buola.Browser","/org/buola/Browser");

    if(cmd_line().ArgCount())
        lProxy.CallIgnore("org.buola.Browser","NewWindow",cmd_line().Args());
    else
        lProxy.CallIgnore("org.buola.Browser","NewWindow",io::get_cwd());

    return false;
}

bool CBrowserApp::Start()
{
    if(!Activate()) return false;

    if(cmd_line().Args().size())
    {
        for(const std::string &a : cmd_line().Args())
        {
            NewWindow(io::uri(a));
        }
    }
    else if(!cmd_line().IsSet(mOptionService))
    {
        NewWindow(io::get_cwd());
    }

    return true;
}

void CBrowserApp::NewWindow(const io::CURI &pURI)
{
    if(pURI.empty()) return;

    for(int i=0;i<mWindows.size();i++)
    {
        if(mWindows[i]->GetWorkingURI()==pURI)
        {
            mWindows[i]->Activate();
            return;
        }
    }

    PBrowserWindow lWindow=new CBrowserWindow(this);
    lWindow->SetWorkingURI(pURI);
    set_main_window(lWindow);
    lWindow->Map();
    mWindows.push_back(lWindow);
}

void CBrowserApp::OnWindowDestroyed(const PBrowserWindow &pWindow)
{
    erase_first_equal(mWindows,pWindow);
}

/*namespace browser*/ } /*namespace buola*/ }
